package com.ys.nms.module.business.controller.admin.linksManual;

import com.baomidou.dynamic.datasource.annotation.Slave;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fhs.core.trans.anno.TransMethodResult;
import com.ys.nms.framework.tenant.core.aop.TenantIgnore;
import com.ys.nms.module.business.libreApi.devices.LibreNmsDeviceClient;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.constraints.*;
import jakarta.validation.*;
import jakarta.servlet.http.*;

import java.util.*;
import java.io.IOException;

import com.ys.nms.framework.common.pojo.PageParam;
import com.ys.nms.framework.common.pojo.PageResult;
import com.ys.nms.framework.common.pojo.CommonResult;
import com.ys.nms.framework.common.util.object.BeanUtils;

import static com.ys.nms.framework.common.pojo.CommonResult.success;

import com.ys.nms.framework.excel.core.util.ExcelUtils;

import com.ys.nms.framework.apilog.core.annotation.ApiAccessLog;

import static com.ys.nms.framework.apilog.core.enums.OperateTypeEnum.*;

import com.ys.nms.module.business.controller.admin.linksManual.vo.*;
import com.ys.nms.module.business.dal.dataobject.linksManual.LinksManualDO;
import com.ys.nms.module.business.service.linksManual.LinksManualService;

@Tag(name = "管理后台 - 线路-手动")
@RestController
@RequestMapping("/business/links-manual")
@Validated
@RequiredArgsConstructor
public class LinksManualController {

    @Resource
    private LinksManualService linksManualService;

    private final LibreNmsDeviceClient deviceClient;

    @PostMapping("/create")
    @Operation(summary = "创建线路-手动")
    public CommonResult<Integer> createLinksManual(@Valid @RequestBody LinksManualSaveReqVO createReqVO) {
        return success(linksManualService.createLinksManual(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新线路-手动")
    public CommonResult<Boolean> updateLinksManual(@Valid @RequestBody LinksManualSaveReqVO updateReqVO) {
        linksManualService.updateLinksManual(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除线路-手动")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteLinksManual(@RequestParam("id") Integer id) {
        linksManualService.deleteLinksManual(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除线路-手动")
    public CommonResult<Boolean> deleteLinksManualList(@RequestParam("ids") List<Integer> ids) {
        linksManualService.deleteLinksManualListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得线路-手动")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<LinksManualRespVO> getLinksManual(@RequestParam("id") Integer id) {
        LinksManualDO linksManual = linksManualService.getLinksManual(id);
        return success(BeanUtils.toBean(linksManual, LinksManualRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得线路-手动分页")
    public CommonResult<PageResult<LinksManualRespVO>> getLinksManualPage(@Valid LinksManualPageReqVO pageReqVO) {
        PageResult<LinksManualDO> pageResult = linksManualService.getLinksManualPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, LinksManualRespVO.class));
    }


    @GetMapping("/list")
    @Operation(summary = "获得线路-手动分页")
    public CommonResult<List<LinksManualRespVO>> getLinksManualList(@Valid LinksManualPageReqVO pageReqVO) {
        List<LinksManualDO> pageResult = linksManualService.getLinksManualList(pageReqVO);
        return success(BeanUtils.toBean(pageResult, LinksManualRespVO.class));
    }


    @GetMapping("/getEChartsLinkData")
    @TenantIgnore
    @Slave
    @Operation(summary = "获得线路-手动分页")
    public CommonResult<EChartsLinkData> getEChartsLinkData(@Valid LinksManualPageReqVO pageReqVO) {
        List<LinksManualDO> list = linksManualService.getLinksManualList(pageReqVO);
        List<LinksManualRespVO> respList = BeanUtils.toBean(list, LinksManualRespVO.class);
        List<EChartsLinkData.Node> listNode = new ArrayList<>();
        List<EChartsLinkData.Link> linkList = new ArrayList<>();
// 用于记录已添加的设备ID（避免重复节点）
        Set<String> addedDeviceIds = new HashSet<>();

        for (LinksManualRespVO respVO : respList) {
            // 1. 处理本地设备节点（使用设备ID作为唯一标识）
            String localDeviceName = respVO.getLocalDeviceName();
            Integer localDeviceId = respVO.getLocalDeviceId();
            if (StringUtils.isNotEmpty(localDeviceName) && localDeviceId != null) {
                String deviceId = String.valueOf(localDeviceId);
                if (!addedDeviceIds.contains(deviceId)) {
                    addedDeviceIds.add(deviceId);

                    EChartsLinkData.Node node = new EChartsLinkData.Node();
                    node.setId(deviceId); // 关键：使用设备ID作为唯一标识
                    node.setName(localDeviceName); // 显示名称
                    String localIcon = deviceClient.getCurrentUrl() + "/images/os/" + respVO.getLocalIcon();
                    node.setSymbol("image://" + localIcon);
                    if (StringUtils.isNotEmpty(respVO.getLocalIcon())) {
                        node.setSymbol("image://" + localIcon);
                    }else{
                        node.setSymbol("image://" + "/src/assets/devices/fwq-5.png");
                    }

                    listNode.add(node);
                }
            }

            // 2. 处理远程设备节点（使用设备ID作为唯一标识）
            String remoteDeviceName = respVO.getRemoteDeviceName();
            Integer remoteDeviceId = respVO.getRemoteDeviceId();
            if (StringUtils.isNotEmpty(remoteDeviceName) && remoteDeviceId != null) {
                String deviceId = String.valueOf(remoteDeviceId);
                if (!addedDeviceIds.contains(deviceId)) {
                    addedDeviceIds.add(deviceId);

                    EChartsLinkData.Node node = new EChartsLinkData.Node();
                    node.setId(deviceId); // 关键：使用设备ID作为唯一标识
                    node.setName(remoteDeviceName); // 显示名称
                    String remoteIcon = deviceClient.getCurrentUrl() + "/images/os/" + respVO.getRemoteIcon();
                    if (StringUtils.isNotEmpty(respVO.getRemoteIcon())) {
                        node.setSymbol("image://" + remoteIcon);
                    }else{
                        node.setSymbol("image://" + "/src/assets/devices/fwq-5.png");
                    }
                    listNode.add(node);
                }
            }

            // 3. 创建链接（使用设备ID作为source/target）
            if (localDeviceId != null && remoteDeviceId != null) {
                // 如果不需要自环（设备连接自身），可过滤
                if (localDeviceId.equals(remoteDeviceId)) {
                    continue;
                }
                EChartsLinkData.Link link = new EChartsLinkData.Link();
                link.setSource(String.valueOf(localDeviceId)); // 关键：使用设备ID
                link.setTarget(String.valueOf(remoteDeviceId)); // 关键：使用设备ID
                link.setValue(respVO.getLocalPortName() + "<->" + respVO.getRemotePortName());
                linkList.add(link);
            }
        }
        EChartsLinkData linkData = new EChartsLinkData();
        linkData.setData(listNode);
        linkData.setLinks(linkList);
        linkData.setRespVO(respList);

        return success(linkData);
    }


    @GetMapping("/export-excel")
    @Operation(summary = "导出线路-手动 Excel")
    @ApiAccessLog(operateType = EXPORT)
    public void exportLinksManualExcel(@Valid LinksManualPageReqVO pageReqVO,
                                       HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<LinksManualDO> list = linksManualService.getLinksManualPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "线路-手动.xls", "数据", LinksManualRespVO.class,
                BeanUtils.toBean(list, LinksManualRespVO.class));
    }

}